$.fn.serializeObject = function () {
    var obj = {};
    var array = this.serializeArray();
    $.each(array, function () {
        if (obj[this.name] !== undefined) {
            if (!obj[this.name].push) {
                obj[this.name] = [obj[this.name]];
            }
            obj[this.name].push(this.value || '');
        } else {
            obj[this.name] = this.value || '';
        }
    });
    return obj;
};

function getValue(data, name) {
    if (!name)
        return "";
    var names = name.split('.');
    for (var i in names)
        if (data) data = data[names[i]];

    if (String(data))
        return data;
    return "";
}

var Table = function (id) {
    var table = $(id + " table");
    var obj = new Object();

    obj.tbody = table.find("tbody")
    obj.template = table.find("tfoot tr")[0];
    obj.url = table.data('url');

    obj.refresh = function (param) {
        var url = this.url;
        var tbody = this.tbody;
        var template = this.template;

        $.ajax({
            url: url,
            type: 'get',
            data: param,
            async: false,
            headers: {'Authentication': localStorage['Authentication']},
            success: function (result) {
                var data = result.list;
                tbody.empty();

                for (var i in data) {
                    var row = data[i];
                    var tr = $(template.cloneNode(true));
                    var tds = tr.children();
                    for (var j = 0; j < tds.length; j++) {
                        var td = $(tds[j]);
                        var name = td.data('name');
                        if (name) {
                            var button = td.find("button")[0];
                            var value = getValue(row, name);
                            if (button)
                                $(button).data("content", value);
                            else
                                td.text(value);
                        }
                    }
                    tr.show();
                    tbody.append(tr);
                }
            }, statusCode: {
                500: function (result) {
                    console.log(result.responseJSON);
                },
                400: function (result) {
                    console.log(result.responseJSON);
                }
            }
        });
    }
    return obj;
}


$("select[data-url]").each(function () {
    var select = this;
    var url = $(select).data("url");
    $.ajax({
        url: url,
        type: "GET",
        async: false,
        headers: {'Authentication': localStorage['Authentication']},
        success: function (result) {
            var data = result;
            var htm = '';
            for (var i in data) {
                var t = data[i];
                htm += '<option value="' + t.value + '">' + t.name;
            }
            $(select).append(htm);
        }
    });
});

var logsTable = new Table("#job-log");
var jobsTable = new Table("#schedule-job");

$("#group").on("change", function () {
    jobsTable.refresh({'group': group.value});
}).trigger("change");

$("#context").on("click", "tr", function (event) {
    var tr = $(event.currentTarget);
    $(tr.parent()).find(".info").removeClass("info");
    tr.addClass("info");
});

$('#job-log-refresh').on('click', function () {
    var button = this;
    button.disabled = true;

    var tds = $("tr.info");
    var jobName = tds.children("[data-name='jobName']").text();
    var jobGroup = tds.children("[data-name='jobGroup']").text();
    var params = {'name': jobName, 'group': jobGroup};
    logsTable.refresh(params);

    setTimeout(function () {
        button.disabled = false
    }, 300);
});


$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

    var activeTab = $(e.target).attr("aria-controls");
    if ('job-log' == activeTab) {
        var tds = $("tr.info");
        var jobName = tds.children("[data-name='jobName']").text();
        var jobGroup = tds.children("[data-name='jobGroup']").text();
        var params = {'name': jobName, 'group': jobGroup};
        logsTable.refresh(params);
    }
});

$('#job-log-modal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    modal.find('textarea').text(button.data('content'));
});

$('#schedule-job-modal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var method = button.data('method');

    var modal = $(this);
    var form = $(modal.find("form"));

    modal.find('.modal-title').text(button.data('title'));
    form.attr("method", method);
    form[0].reset();

    if (method == "PUT" || method == "CLONE") {
        var tds = $("tr.info td");
        for (var j = 0; j < tds.length; j++) {
            var td = $(tds[j]);
            var name = td.data('name');
            var value = td.text();
            form.find("[name='" + name + "']").val(value);
        }
    }

    if (method == "PUT") {
        form.find("[name='jobName']").attr('readonly', true);
        form.find("[name='jobGroup']").attr('readonly', true);
    } else {
        form.find("[name='jobName']").attr('readonly', false);
        form.find("[name='jobGroup']").attr('readonly', false);
    }
});

$(".submit-item").on("click", function () {
    var form = $($(this).parents("form"));
    var method = form.attr("method");
    if (method == 'CLONE')
        method = 'POST';
    var action = form.attr('action');
    var data = form.serializeObject();

    action += "/" + data['jobGroup'] + "/" + data['jobName'];

    $.ajax({
        url: action,
        type: method,
        contentType: 'application/json',
        headers: {'Authentication': localStorage['Authentication']},
        data: JSON.stringify(data),
        success: function (result) {
            if (result.success) {
                jobsTable.refresh({'group': group.value});
                $('#schedule-job-modal').modal('hide');
            }
        },
        statusCode: {
            500: function (result) {
                $('#detail-message').hide().html('<label class="label label-danger">' + result.responseJSON.msg + '</label>').show(300);
            },
            400: function (result) {
                $('#detail-message').hide().html('<label class="label label-danger">' + result.responseJSON.msg + '</label>').show(300);
            }
        }
    });
});

$(".do-post").on("click", function () {
    var button = $(this);
    var url = button.data("url");
    var tr = $("tr.info");

    var jobName = tr.children("[data-name='jobName']").text();
    var jobGroup = tr.children("[data-name='jobGroup']").text();
    url = "schedule-job/" + jobGroup + "/" + jobName + "/" + url;

    $.ajax({
        url: url,
        type: 'POST',
        headers: {'Authentication': localStorage['Authentication']},
        success: function (result) {
            if (result.data) {
                jobsTable.refresh({'group': group.value});
            } else {
                alert(result.msg);
                console.log(result.stackMsg);
            }
        }
    });
});